package com.ronghui.cash.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.ronghui.cash.util.CodecUtil;
import com.ronghui.cash.util.IdWorker;
import com.ronghui.cash.util.StringUtil;
import com.ronghui.cash.vo.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 这个基础类是单例类，要特别注意属性
 * 
 * @author wiki
 * 
 */
public class BaseController {

	@Autowired
	public HttpServletRequest request;// 用@Autowired注入的request不会有单例的问题
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	protected Response failure(String message) {
		return new Response().failure(message);
	}

	protected Response failure(String message,Object data) {
		return new Response().failure(message,data);
	}


	protected Response failure() {
		return new Response().failure();
	}

	protected Response success(Object data) {
		return new Response().success(data);
	}

	protected Response success() {
		return new Response().success();
	}

	@Autowired
	RedisTemplate redisTemplate;

	@Autowired
	IdWorker idWorker;

	protected Long getNextId(){
		return idWorker.nextId();
	}
	protected Long getUserId(){
		return (Long)redisTemplate.opsForValue().get("access:token:" + request.getParameter("token"));
	}

	protected String setTokenOnRedis(Long userId){
		String token = CodecUtil.createUUID();
		int exptime = 3600*24*30;//30天
		redisTemplate.opsForValue().set("access:token:"+token,userId,exptime, TimeUnit.SECONDS);
		return token;
	}

	/**
	 * <p>
	 * 获取分页对象
	 * </p>
	 * 
	 * @return
	 */
	protected <T> Page<T> getPage() {
		int limit = 10, page = 1;
		if (request.getParameter("limit") != null && StringUtil.isNumeric(request.getParameter("limit"))) {
			limit = Integer.parseInt(request.getParameter("limit"));
		}
		if (request.getParameter("page") != null && StringUtil.isNumeric(request.getParameter("page"))) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		return new Page<T>(page, limit);
	}


}
